import joblib
import numpy as np
from skimage import io, color
from skimage.transform import resize
from skimage.feature import hog

# 图像预处理和特征提取
def extract_features(image_path, img_size=(1024, 691)):
    image = io.imread(image_path)
    if len(image.shape) == 3:  # 如果是彩色图像
        image = color.rgb2gray(image)
    image_resized = resize(image, img_size)
    features, _ = hog(image_resized, block_norm='L2-Hys', pixels_per_cell=(16, 16),
                      cells_per_block=(2, 2), visualize=True)
    return features

# 预测函数
def predict(image_path, model_path='svm_hog_best_model.pkl', label_encoder_path='label_encoder.pkl'):
    clf = joblib.load(model_path)
    label_encoder = joblib.load(label_encoder_path)

    features = extract_features(image_path)
    features = features.reshape(1, -1)
    prediction = clf.predict(features)
    predicted_class = label_encoder.inverse_transform(prediction)
    return predicted_class[0]

# 示例用法
image_path = r'D:\develop\PythonCode\python基础\附_项目实战\九_薄膜图片级别分类\test_img\test_605.tif'  # 替换为实际的图片路径
predicted_class = predict(image_path)
print("Predicted Class:", predicted_class)
